<template>
  <div>
    <header class="je-header">
      <div
        @tap="goBack($event)"
        class="back-btn mui-action-back">
        <i class="jeicon jeicon-angle-left" />
      </div>
      <div class="title">日程</div>
    </header>
    <div
      class="all_schedule"
    >
      <div
        id="refreshContainer"
        class="item_wrp mui-scroll-wrapper"
      >
        <div
          class="mui-scroll"
          style="background: #ffffff;"
        >
          <div
            v-if="newList.length > 0"
            class="items-wrp"
          >
            <div
              v-for="(item, index) in newList"
              v-if="!isInit || item.ymFormat > initDate"
              :key="index"
              class="items"
            >
              <div
                v-if="(index > 0 && item.item_title !== newList[index-1].item_title) || index === 0"
                class="title"
              >
                <div class="title_date">
                  <div class="title_line" />
                  {{ item.item_title }}
                </div>
              </div>
              <div
                @tap="goDetail(item)"
                class="item_content je-audio-btn"
              >
                <div
                  v-if="(index > 0 && item.showDays !== newList[index-1].showDays || index === 0)"
                  :class="{'showBorder':item.showBorder}"
                  class="time"
                >
                  {{ item.showDays2Msg }}
                  <!-- <div>
                    {{ item.showDays }}
                  </div> -->
                  <!-- <div>{{ item.showHours }}</div> -->
                </div>
                <div
                  v-else
                  :class="{'showBorder':item.showBorder}"
                  class="time"
                />
                <div class="content_title">
                  <div class="title">
                    <div
                      :style="{background: item.CALENDAR_COLOR || '#386BD0'}"
                      class="type"
                    />
                    {{ shortTitle(item.CALENDAR_TITLE) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div
            v-else
            class="items-wrp"
          >
            <p class="no_calendar">
              暂无日程
            </p>
          </div>
        </div>
      </div>
    </div>
</div>
</template>

<script>
import {
  openWindow,
} from '@/helper';

export default {
  name: 'AllSchedule',
  data() {
    return {
      dataList: [],
      newList: [],
      initDate: '',
      upDate: '',
      downDate: '',
      refreshDirection: 'up',
      isInit: true,
    };
  },
  created() {},
  mounted() {
    const that = this;
    const { selectMonth } = plus.webview.currentWebview();
    this.initDate = this.changeMonth(selectMonth, 1); // YYYY-MM
    this.upDate = this.changeMonth(selectMonth, 1);
    this.downDate = selectMonth;
    window.addEventListener('research', (item) => {
      that.upDate = item.detail.upDate;
      this.$nextTick(() => {
        that.dataList = [];
        that.initData(that.upDate);
      });
    });
    that.pullrefresh = mui('#refreshContainer').pullRefresh4HTML({
      down: {
        callback() {
          that.refreshDirection = 'down';
          that.initData(that.downDate, (data) => {
            const rows = data.rows || [];
            that.pullrefresh.endPulldownToRefresh();
            that.dataList = rows.concat(that.dataList);
            that.downDate = data.startMonth;
            that.isInit = false;
            that.dataList.length > 0 && that.handleData();
            JE.msg('加载成功');
          });
        },
      },
      up: {
        callback() {
          that.refreshDirection = 'up';
          that.initData(that.upDate, (data) => {
            const rows = data.rows || [];
            that.pullrefresh.endPullupToRefresh(false);
            that.dataList = that.dataList.concat(rows);
            that.upDate = data.endMonth;
            // that.isInit = false;
            that.dataList.length > 0 && that.handleData();
            JE.msg('加载成功');
          });
        },
      },
    });
    this.initData(this.upDate);
  },
  methods: {
    async initData(year, fn) {
      const userInfo = JE.getCurrentUser();
      const params = {
        tableCode: 'JE_SYS_CALENDAR',
        limit: -1,
        permSql: `AND (SY_CREATEUSER='${userInfo.userCode}' OR CALENDAR_GROUPID IN (SELECT GROUPUSER_GROUP_ID FROM JE_SYS_GROUPUSER WHERE GROUPUSER_USERID='${userInfo.id}') OR CALENDAR_GROUPID IN (SELECT JE_SYS_CALENDARGROUP_ID FROM JE_SYS_CALENDARGROUP WHERE SY_CREATEUSER='${userInfo.userCode}'))`,
        // whereSql: `AND CALENDAR_STARTTIME>='${searchYear}-01-01' AND CALENDAR_ENDTIME<='${searchYear}-12-31'`,
        whereSql: '',
        page: 1,
        start: 0,
        dateStr: year,
        pageNext: this.refreshDirection,
        step: 3,
      };
      // const data = await JE.ajax({ url: `/je/calendar/calendar/load?_dc=${new Date().getTime()}`, params, async: false });
      const data = await JE.ajax({ url: '/je/calendar/calendar/loadAppCalendar', params, async: false });
      if (fn && typeof (fn) === 'function') {
        fn(data);
        return;
      }
      this.dataList = this.dataList.concat(data.rows);
      this.dataList.length > 0 && this.handleData();
      this.upDate = data.endMonth;
      this.downDate = data.startMonth;
    },
    /** 处理数据格式
     *  按照日程首页格式拆分
     *  第一天为HH点开始
     *  最后一天为HH点结束
     *  余下为全天
     */
    handleData() {
      this.newList = [];
      const dataList = this.delDuplicate(this.dataList);
      dataList.forEach((item) => {
        const diffDays = this.diffDays(new Date(item.CALENDAR_STARTTIME.replaceAll('-', '/')), new Date(item.CALENDAR_ENDTIME.replaceAll('-', '/')));
        if (diffDays > 0) {
          for (let i = 0; i <= diffDays; i++) {
            const newItem = JSON.parse(JSON.stringify(item));
            const dayTimes = new Date(newItem.CALENDAR_STARTTIME.replaceAll('-', '/')).getTime() + (86400000 * i);
            const dayTimesList = JE.dateFormat(new Date(dayTimes), 'YYYY-MM-DD').split('-');
            newItem.showDays = `${dayTimesList[1]}-${dayTimesList[2]}`;
            newItem.ymFormat = `${dayTimesList[0]}-${dayTimesList[1]}`;
            newItem.showDays2Msg = `${newItem.showDays.split('-')[1]}日`;
            newItem.item_title = this.getYear(dayTimes);
            if (i === 0) {
              newItem.showHours = `${this.gh(newItem.CALENDAR_STARTTIME)}点开始`;
            } else if (i === diffDays - 0) {
              newItem.showHours = `${this.gh(newItem.CALENDAR_ENDTIME)}点结束`;
            } else {
              newItem.showHours = '全天';
            }
            this.newList.push(newItem);
          }
        } else {
          item.item_title = this.getYear(item.CALENDAR_STARTTIME);
          item.showHours = this.getHour(item);
          item.showDays = this.getMonth(item.CALENDAR_STARTTIME);
          item.showDays2Msg = `${item.showDays.split('-')[1]}日`;
          item.ymFormat = JE.dateFormat(item.CALENDAR_STARTTIME, 'YYYY-MM');
          this.newList.push(item);
        }
      });
      // 排序
      this.newList = this.bubbleSort(this.newList);
      const len = this.newList.length;
    },
    // 去重
    delDuplicate(list) {
      // JE_SYS_CALENDAR_ID
      const newList = [];
      const obj = {};
      list.forEach((item) => {
        if (!obj[item.JE_SYS_CALENDAR_ID]) {
          newList.push(item);
          obj[item.JE_SYS_CALENDAR_ID] = true;
        }
      });
      return newList;
    },
    changeMonth(d, count) {
      const date = new Date(`${d.replaceAll('-', '/')}/01`);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      if (count > 0) {
        if (m === 1 || m === '1' || m === '01') {
          y -= count;
          m = 12;
        } else {
          m -= count;
        }
      } else if (m === 12 || m === '12') {
        y -= count;
        m = 1;
      } else {
        m -= count;
      }
      m = m < 10 ? `0${m.toString()}` : m;
      return JE.dateFormat(new Date(`${y}/${m}/01`), 'YYYY-MM');// ios兼容性用/代替-
    },
    diffDays(startTime, endTime) {
      const diff = endTime.getTime() - startTime.getTime();
      // return (diff / 1000 / 60 / 60 / 24).toFixed();
      return Math.floor(diff / 1000 / 60 / 60 / 24);
    },
    getYear(item) {
      const date = JE.dateFormat(item, 'YYYY-MM-DD').split('-');
      return `${date[0]}年${date[1]}月`;
    },
    getMonth(item) {
      if (!item) return;
      const date = JE.dateFormat(item).split(' ')[0];
      const md = date.split('-');
      return `${md[1]}-${md[2]}`;
    },
    getHour(item) {
      if (item.CALENDAR_STARTTIME.split(' ')[0] === item.CALENDAR_ENDTIME.split(' ')[0]) {
        return `${this.gh(item.CALENDAR_STARTTIME)}点-${this.gh(item.CALENDAR_ENDTIME)}点`;
      }
      return `${this.gh(item.CALENDAR_STARTTIME)}点开始`;
    },
    gh(date) {
      const time = JE.dateFormat(date).split(' ')[1];
      return time.split(':')[0];
    },
    bubbleSort(arr) {
      let i = arr.length - 1;
      while (i > 0) {
        let pos = 0;
        for (let j = 0; j < i; j += 1) {
          if (arr[j].showDays > arr[j + 1].showDays) {
            pos = j;
            // eslint-disable-next-line
            const tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp;
          }
        }
        i = pos;
      }
      // 处理日期下划线
      arr = this.timeBorder(arr);
      return arr;
    },
    timeBorder(arr) {
      for (let i = 0; i < arr.length; i++) {
        arr[i].showBorder = false;
        // 最后一条去掉border-bottom
        if (index === arr.length - 1) {
          arr[i].showBorder = false;
        }
        if (arr[i + 1] && arr[i].showDays !== arr[i + 1].showDays && arr[i].showDays.split('-')[0] === arr[i + 1].showDays.split('-')[0]) {
          arr[i].showBorder = true;
        }
      }
      return arr;
    },
    goDetail(item) {
      openWindow({
        url: './pages_calendardetail_index.html',
        id: '__calendarDetailView',
        title: '创建日程',
        extras: {
          item,
          type: 'edit',
          upDate: this.initDate,
        },
        hideNView: true,
      });
    },
    shortTitle(title) {
      const maxlength = 13;
      if (title.length > maxlength) {
        return `${title.slice(0, maxlength)}...`;
      }
      return title;
    },
  },
};
</script>

<style lang="less" scoped>
  @import '~@/theme/index.less';
  p {
    margin: 0;
  }
  .all_schedule {
    position: absolute;
    top: unit(45 * @hd, px);
    right: 0;
    bottom: 0;
    left: 0;
    background: #ffffff;
    .item_wrp {
      .items {
        width: 100%;
        .title {
          background-color:rgba(77, 111, 254, 0.1);
          padding: 10 * @hd 15 * @hd;
          align-items: center;
          .title_date {
            color:#4D6FFE;
            font-size: 16 * @hd;
            flex: 1;
            padding-left: 10px;
            position: relative;
            .title_line {
              background-color: #4D6FFE;
              width: 4px;
              height: auto;
              border-radius: 4px;
              position: absolute;
              top: 0;
              left: 0;
              bottom: 0;
            }
          }
        }
        .item_content {
          padding: 0 15 * @hd;
          color: @color-text-base;
          display: flex;
          // border-bottom: 1px solid #f5f5f5;
          background: #ffffff;
          .time {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 15 * @hd;
            width: 80 * @hd;
            padding: 6px 0;
            border-bottom: 1px solid transparent;
            // > div {
            //   font-size: 11 * @hd;
            //   height: 15 * @hd;
            //   line-height: 15 * @hd;
            //   &:last-child {
            //     margin-top: 2px;
            //   }
            // }
            &.showBorder {
              border-bottom: 1px solid #f5f5f5;
            }
          }
          .content_title {
            font-size: 15 * @hd;
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: flex-start;
            padding: 6px 0;
            border-bottom: 1px solid #f5f5f5;
            .title {
              flex: 1;
              background: #ffffff;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
              position: relative;
              .type {
                position: absolute;
                left: 3px;
                top: 9px;
                bottom: 9px;
                width: 2px;
                border-radius: 2px;
              }
            }
          }
        }
        &:active {
          .item_content {
            background: #eeeeee;
            .content_title {
              .title {
                background: #eaebef;
              }
            }
          }
        }
      }
      .no_calendar {
        margin: 0;
        text-align: center;
        height: 44 * @hd;
        line-height: 44 * @hd;
        color: #A9ABA9;
        font-size: 17 * @hd;
      }
    }
  }
</style>
<style lang="less">
@import "~@/theme/index.less";
.mui-scrollbar {
  display: none !important;
}
</style>
